import django
from django import http
from django import shortcuts

from google.appengine.api import images

from blog.models import *
from blog.helper import *
from blog.sql import *
from blog.sessions import *
from conf.settings import *
 

def signout(request):
    session = Session()
    user = users.GetCurrentUser()
    session.delete()
    linkLogout = users.CreateLogoutURL('/')
    return http.HttpResponseRedirect(linkLogout)

def list(request):
    params = {}
    where = ""
    now = datetime.datetime.now()
    
    items = VMember.all()
    params['Title'] = 'List Member' 
    params['items'] = items
    return respond(request, None, 'vmember_list', params)


def add(request):
    
    return edit(request, None)

def edit(request, idItem):
    member = Permission(1)
    params = {}
    params['Title'] = 'Add/Edit Member'
    item = None
    if idItem:
        item = VMember.get_by_id(int(idItem))
        if item is None:
            return http.HttpResponseNotFound('No Item')
        else:
            if item.user != member.user:
                return respond(request, None, 'message_box', {"message":"No Permission."})
    else:
        if member :
            return http.HttpResponseRedirect('/')
    params['item'] = item
    
    if not request.POST:
        return respondMember(request, None, 'vmember_edit', params)
  
    if item is None:
        item = VMember()
    if request.FILES:
        img_data    = request.FILES['image']['content']
        img         = images.Image(img_data)
        img.im_feeling_lucky()
        img.resize(150, 150)
        img_data    = img.execute_transforms(images.PNG)
        item.image  = img_data 
    try:            
        item.name      = unicode(SafePost('name', '', request), 'utf-8')
        
    except db.Error, err:
        params['err'] = err
        params['item'] = item
        return respondMember(request, None, 'vmember_edit', params)
  
    item.put()

    return http.HttpResponseRedirect('/')

def view(request, idItem):
    params = {}
    params['Title'] = 'View Article'
    
    item = None
    if idItem:
        item = VMember.get_by_id(int(idItem))
        if item:
            params['item'] = item
            params['Title'] = item.title
            return respond(request, None, 'vmember_view', params)
    
    return respond(request, None, 'message_box', {"message":"No Article."})

def image(request,idItem):
    if idItem:
        item= VMember.get_by_id(int(idItem))
        if item.image:
            return http.HttpResponse(item.image,mimetype='image/png')
    return  http.HttpResponse('')

